package com.design.twords.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.design.twords.R;
import com.design.twords.adatper.ChangePlanAdapter;
import com.design.twords.config.ConfigData;
import com.design.twords.config.ConstantValue;
import com.design.twords.controller.TimeController;
import com.design.twords.database.BookList;
import com.design.twords.database.Phrase_all;
import com.design.twords.database.Phrase_learn;
import com.design.twords.database.RelWord_all;
import com.design.twords.database.RelWord_learn;
import com.design.twords.database.Sentence_all;
import com.design.twords.database.Sentence_learn;
import com.design.twords.database.Translation_all;
import com.design.twords.database.Translation_learn;
import com.design.twords.database.UserConfig;
import com.design.twords.database.Word_all;
import com.design.twords.database.Word_learn;
import com.design.twords.entity.ItemWordBook;
import com.design.twords.json.JsonForDatabase;
import com.design.twords.utils.FileUtil;
import com.design.twords.utils.MyApplication;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Create by Alen
 * Time:  23:11
 */
public class ChangePlanActivity extends AppCompatActivity {

    private static final String TAG = "ChangePlanActivity";

    private ImageView img_back;
    private RecyclerView booklist;

    private ProgressDialog progressDialog;
    private MyDialogFragment myDialogFragment;

    private ChangePlanAdapter cpAdapter;

    private ArrayList<ItemWordBook> wordBooks = new ArrayList<>();

    private int[] bookIds = new int[]{ConstantValue.CET_4, ConstantValue.CET_6, ConstantValue.KAOYAN,
            ConstantValue.CET_6_ALL, ConstantValue.KAOYAN_ALL};

    private static final int FINISH = 1;
    private static final int DOWN_DONE = 2;
    private static final int FAIL = 3;
    private static final int DOWN_BOOK = 4;
    private static final int GO_LEARN = 5;

    private static final int PERMISSION_REQUESTCODE = 100;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case FINISH:
                    showProgressDialog("解析完成");
                    break;
                case DOWN_DONE:
                    showProgressDialog("已下载完成，正在正在装入数据...");
                    break;
                case FAIL:
                    showProgressDialog("解析出错,请重试");
                    progressDialog.setCancelable(true);
                    break;
                case DOWN_BOOK:
                    showProgressDialog("数据正在下载...");
                    break;
                case GO_LEARN:
                    showProgressDialog("正在前往背诵任务...");
                    break;
            }
        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_changeplan);
        MyApplication.getInstance().addActivity(this);
        initView();



        for (int id: bookIds){
            ItemWordBook item = new ItemWordBook(id, ConstantValue.bookNameById(id), ConstantValue.wordTotalNumberById(id),"有道考神",ConstantValue.bookPicById(id),false);
            wordBooks.add(item);
        }

        booklist.setLayoutManager(new LinearLayoutManager(this));
        cpAdapter = new ChangePlanAdapter(wordBooks, this, R.layout.item_booklist);
        booklist.setAdapter(cpAdapter);


        cpAdapter.setListener(new ChangePlanAdapter.ItemClickListener() {
            @Override
            public void itemClickListener(int position) {
                ItemWordBook itemWordBook = wordBooks.get(position);

                myDialogFragment = new MyDialogFragment(ChangePlanActivity.this);
                setDetail(itemWordBook);
            }

        });

        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });


    }

    private void setDetail(ItemWordBook item) {

        myDialogFragment.bookname.setText(item.getBookName());
        myDialogFragment.wordnumb.setText(item.getBookWordNum()+"");
        myDialogFragment.showNow(getSupportFragmentManager(), "myDialogFragment");
        myDialogFragment.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String day_words = myDialogFragment.daywords.getText().toString();
                Log.i(TAG, "day_words" + day_words);

                List<BookList> bookLists = LitePal.where("bookid = ?", item.getBookId()+"").find(BookList.class);
                if (bookLists.size() <= 0){
                    //书籍未下载
                    //下载书籍
                    downLoadBook(item);

                }
                //书籍已下载 直接开始背诵模式
                //将单词数据装入到 Word_learn 表中
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        DataTransfer(item.getBookId());
                        Message msg = new Message();
                        msg.what = DOWN_DONE;
                        handler.sendMessage(msg);

                        UserConfig userConfig = new UserConfig();
                        userConfig.setUserId(ConfigData.getUserId());
                        userConfig.setCurrentBookId(item.getBookId());
                        userConfig.setDaywords(Integer.parseInt(day_words));
                        userConfig.setLastStartTime(TimeController.getCurrentTimeStamp());
                        userConfig.save();

                        Intent intent = new Intent(ChangePlanActivity.this, LearnWordActivity.class);
                        try {
                            Message msg1 = new Message();
                            msg1.what = GO_LEARN;
                            handler.sendMessage(msg1);
                            
                            Thread.sleep(3000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        startActivity(intent);
                        progressDialog.dismiss();
                        finish();
                    }
                }).start();



            }
        });

    }

    private void DataTransfer(int bookId) {
        //首先清空背诵数据库
        if (!LitePal.findAll(Word_learn.class).isEmpty()){
            LitePal.deleteAll(Word_learn.class);
            LitePal.deleteAll(Translation_learn.class);
            LitePal.deleteAll(Sentence_learn.class);
            LitePal.deleteAll(RelWord_learn.class);
            LitePal.deleteAll(Phrase_learn.class);
        }

        String wordbook = ConstantValue.getTypeById(bookId);

        //配置单词基本信息
        List<Word_all> word_alls = LitePal.where("wordBook = ?", wordbook).find(Word_all.class);
        for (Word_all wall: word_alls){
            Word_learn word_learn = new Word_learn();
            //设置id
            word_learn.setWordId(wall.getWordId());
            //设置归属书籍
            word_learn.setWordBook(wordbook);
            //设置单词
            word_learn.setWord(wall.getWord());
            //设置音标
            word_learn.setUsPhone(wall.getUsPhone());
            word_learn.setUkPhone(wall.getUkPhone());
            //设置巧记方法
            word_learn.setRemMethod(wall.getRemMethod());
            //设置备注
            word_learn.setRemark(wall.getRemark());
            //设置是否收藏
            word_learn.setIsCollected(wall.getIsCollected());

            word_learn.save();
        }
        //配置其他信息
        List<Translation_all> translation_alls = LitePal.where("wordBook = ?", wordbook).find(Translation_all.class);
        for (Translation_all trall : translation_alls){
            Translation_learn tranlean = new Translation_learn();
            tranlean.setWordId(trall.getWordId());
            tranlean.setWordType(trall.getWordType());
            tranlean.setCHSMeaning(trall.getCHSMeaning());
            tranlean.setENMeaning(trall.getENMeaning());
            tranlean.save();
        }
        List<Sentence_all> sentence_alls = LitePal.where("wordBook = ?", wordbook).find(Sentence_all.class);
        for (Sentence_all sentall : sentence_alls){
            Sentence_learn sentlearn = new Sentence_learn();
            sentlearn.setWordId(sentall.getWordId());
            sentlearn.setSentence(sentall.getSentence());
            sentlearn.setTran(sentall.getTran());
            sentlearn.save();
        }
        List<Phrase_all> phrase_alls = LitePal.where("wordBook = ?", wordbook).find(Phrase_all.class);
        for (Phrase_all phraseall : phrase_alls){
            Phrase_learn phraselearn = new Phrase_learn();
            phraselearn.setWordId(phraseall.getWordId());
            phraselearn.setPhrase(phraseall.getPhrase());
            phraselearn.setTrans(phraseall.getTrans());
            phraselearn.save();
        }
        List<RelWord_all> relWord_alls = LitePal.where("wordBook = ?", wordbook).find(RelWord_all.class);
        for (RelWord_all word_all : relWord_alls){
            RelWord_learn word_learn = new RelWord_learn();
            word_learn.setWordId(word_all.getWordId());
            word_learn.setWrodType(word_all.getWrodType());
            word_learn.setWord(word_all.getWord());
            word_learn.setTran(word_all.getTran());
            word_learn.save();
        }

        List<Word_learn> all = LitePal.findAll(Word_learn.class);
        Log.i(TAG, "word_learn.size"+all.size());


    }

    public void downLoadBook(ItemWordBook item){
        //判断权限
        JudgePermission();

        Message msg = new Message();
        msg.what = DOWN_BOOK;
        handler.sendMessage(msg);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            OkHttpClient client = new OkHttpClient();
                            Request request = new Request.Builder()
                                    .url(ConstantValue.bookDownLoadAddressById(item.getBookId()))
                                    .build();
                            Response response = client.newCall(request).execute();
                            Message message = new Message();
                            message.what = DOWN_DONE;
                            handler.sendMessage(message);
                            //将文件下载到本地
                            FileUtil.BytesToFile(response.body().bytes(),ChangePlanActivity.this.getFilesDir() + "/" + ConstantValue.DIR_TOTAL,
                                    ConstantValue.bookFileNameById(item.getBookId()));
                            //解压文件
                            FileUtil.unZipFile(ChangePlanActivity.this.getFilesDir() + "/" + ConstantValue.DIR_TOTAL + "/" + ConstantValue.bookFileNameById(item.getBookId()),
                                    ChangePlanActivity.this.getFilesDir() + "/" + ConstantValue.DIR_TOTAL + "/" + ConstantValue.DIR_AFTER_FINISH,false);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        //从本地加载json 文件 解析后存入到数据库中
                        boolean flag = JsonForDatabase.analyseJson(FileUtil.readLocalJson(ChangePlanActivity.this.getFilesDir() + "/" + ConstantValue.DIR_TOTAL + "/"
                                        + ConstantValue.DIR_AFTER_FINISH + "/" +ConstantValue.bookFileNameById(item.getBookId()).replace(".zip",".json")),
                                ConstantValue.getTypeById(item.getBookId()));
                        if(flag){

                            //将书籍信息存入到 Booklist 表中
                            BookList book = new BookList();
                            book.setBookId(item.getBookId());
                            book.setBookname(item.getBookName());
                            book.setWordcounts(item.getBookWordNum());
                            book.setInUse(1);
                            book.setCreatetime(TimeController.getStringDateDetailNoS(TimeController.getCurrentTimeStamp()));
                            book.save();
                            Log.i(TAG, "书籍下载成功");

                            Message message = new Message();
                            message.what = FINISH;
                            handler.sendMessage(message);
                        }
                        else{
                            Message message = new Message();
                            message.what = FAIL;
                            handler.sendMessage(message);
                        }

                    }
                });
                thread.start();
            }
        },500);

    }


    private void showProgressDialog(String content) {
        progressDialog = new ProgressDialog(ChangePlanActivity.this);
        progressDialog.setTitle("请稍后");
        progressDialog.setMessage(content);
        progressDialog.setCancelable(true);
        progressDialog.show();
    }


    private void initView() {
        img_back = findViewById(R.id.changeplan_back);
        booklist = findViewById(R.id.chanplan_book);

    }

    private void JudgePermission(){
        if (ContextCompat.checkSelfPermission(this, Manifest.permission_group.STORAGE) != PackageManager.PERMISSION_GRANTED){
            // 请求申请权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission_group.STORAGE},
                    PERMISSION_REQUESTCODE);

            // 未获得权限
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.CAMERA)) {
                //说明用户明确拒绝了某个权限，我们应该在这里做出提示给用户，说清楚此权限的用户
                Toast.makeText(ChangePlanActivity.this,"没有权限",Toast.LENGTH_LONG).show();
                onStart();

            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode != PERMISSION_REQUESTCODE) {
            Toast.makeText(ChangePlanActivity.this,"没有存储权限",Toast.LENGTH_LONG).show();
            onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.getInstance().removeActivity(this);
    }

    public static class MyDialogFragment extends DialogFragment {
        private EditText daywords;
        private Button button;
        private CardView chanplan_card;
        private TextView bookname, wordnumb, finishday;
        private View itemview;
        private LayoutInflater inflate;

        public MyDialogFragment(Context context) {
            inflate = LayoutInflater.from(context);
            itemview = inflate.inflate(R.layout.dialog_fragment,null);

            chanplan_card = itemview.findViewById(R.id.chanplan_card);
            bookname = itemview.findViewById(R.id.changeplan_bookname);
            wordnumb = itemview.findViewById(R.id.changeplan_wordnumb);
            daywords = itemview.findViewById(R.id.changeplan_dayword);
            button = itemview.findViewById(R.id.changeplan_bt);
            finishday = itemview.findViewById(R.id.changeplan_day);
        }

        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
            return itemview;
        }

        @Override
        public void onActivityCreated(@Nullable Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            daywords.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }
                @Override
                public void afterTextChanged(Editable s) {
                    String strdayword = daywords.getText().toString();
                    if(!strdayword.equals("")){
                        try {
                            int s1 = Integer.valueOf(strdayword);
                            int s2 = Integer.valueOf(wordnumb.getText().toString());
                            if(s1 > 0 && s1 < s2){
                                finishday.setText((s2/s1)+"");
                            }else {
                                Toast.makeText(getContext(),"请输入正确的数值", Toast.LENGTH_LONG).show();
                            }
                        }catch (Exception e){
                            Toast.makeText(getContext(),"请输入正确的数值", Toast.LENGTH_LONG).show();
                        }
                    }
                }
            });


        }

        @Override
        public void show(@NonNull FragmentManager manager, @Nullable String tag) {
            super.show(manager, tag);
        }

    }



}
